//
//  UserAccount.swift
//  01sinablog
//
//  Created by ZhangZiang on 15/12/13.
//  Copyright © 2015年 ZhangZiang. All rights reserved.
//

import UIKit

class UserAccount: NSObject,NSCoding {

    var access_token : String?
    
    var expires_in : NSTimeInterval = 0 {
        didSet
        {
            //获得token的具体的过期日期
            expires_date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    
    var remind_in : String?
    
    var uid : String?
    //为了防止token过期
    var expires_date : NSDate?
    
    //用户的信息
    var avatar_large : String?
    var name : String?
    
    func userAccountWithDict(dict : [String : AnyObject]) -> UserAccount
    {
        self.setValuesForKeysWithDictionary(dict)
        
        return self
    }
    
    override init() {
        super.init()
    }
    
    //获取在本地的用户信息(用类方法,因为这样可以在方法里创建一个对象并返回)
    class func loadAccount() -> UserAccount?
    {
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! as NSString).stringByAppendingPathComponent("account.plist")
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? UserAccount
        {
            //判断,如果过期日期大于现在日期(降序),就返回account
            if account.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending
            {
            return account
            }
        }
        return nil
    }
    
    //保存account的方法
    func saveAccount()
    {
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! as NSString).stringByAppendingPathComponent("account.plist")
        
        //保存
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
    }
    
    //归档和解档
    //归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(remind_in, forKey: "remind_in")
        aCoder.encodeObject(uid, forKey: "uid")

        aCoder.encodeObject(expires_date, forKey: "expires_date")
    }
    
    //解档
    required init?(coder aDecoder: NSCoder) {
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        remind_in = aDecoder.decodeObjectForKey("remind_in") as? String
        uid = aDecoder.decodeObjectForKey("uid") as? String
        
        expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
    }
}
